package org.zoomdev.zoom.aop.utils;

import org.objectweb.asm.AnnotationVisitor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomAnnotationVisitor extends AnnotationVisitor {
    private final Map<String, Object> annotationValues = new HashMap<>();

    public CustomAnnotationVisitor(int api, AnnotationVisitor av) {
        super(api, av);
    }

    @Override
    public void visit(String name, Object value) {
        // 处理基本类型、字符串等简单值
        annotationValues.put(name, value);
        super.visit(name, value);
    }

    @Override
    public void visitEnum(String name, String descriptor, String value) {
        // 处理枚举类型值
        annotationValues.put(name, value);
        super.visitEnum(name, descriptor, value);
    }

    @Override
    public AnnotationVisitor visitAnnotation(String name, String descriptor) {
        // 处理嵌套注解
        Map<String, Object> nestedAnnotation = new HashMap<>();
        annotationValues.put(name, nestedAnnotation);
        return new CustomAnnotationVisitor(api, super.visitAnnotation(name, descriptor)) {
            @Override
            public void visitEnd() {
                // 收集嵌套注解的值
                nestedAnnotation.putAll(annotationValues);
            }
        };
    }

    @Override
    public AnnotationVisitor visitArray(String name) {
        // 处理数组类型的值
        List<Object> arrayValues = new ArrayList<>();
        annotationValues.put(name, arrayValues);

        return new AnnotationVisitor(api, super.visitArray(name)) {
            @Override
            public void visit(String name, Object value) {
                arrayValues.add(value);
                super.visit(name, value);
            }

            @Override
            public void visitEnum(String name, String descriptor, String value) {
                arrayValues.add(value);
                super.visitEnum(name, descriptor, value);
            }

            @Override
            public AnnotationVisitor visitAnnotation(String name, String descriptor) {
                // 数组中嵌套注解
                Map<String, Object> nestedAnnotation = new HashMap<>();
                arrayValues.add(nestedAnnotation);
                return new CustomAnnotationVisitor(api, super.visitAnnotation(name, descriptor)) {
                    @Override
                    public void visitEnd() {
                        nestedAnnotation.putAll(annotationValues);
                    }
                };
            }
        };
    }

    public Map<String, Object> getAnnotationValues() {
        return annotationValues;
    }
}